﻿Imports System.Threading
Imports System.Net
Imports System.Net.Sockets
Imports System.IO
Imports System.Data.OleDb
Imports System.IO.ports
Imports System.Math
Imports System.Windows.Forms
Imports Microsoft.VisualBasic
Public Class AccessControl
    Public ScpwFlg As Boolean = False
    Public Scpw As Integer = 0
    Public OldPW As String = ""
    Public NewPW As String = ""
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitP.Click
        End
    End Sub

    Private Sub AccessControl_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ConnectionServerDatabase()
        If GetAddressStr() = False Then
            MessageBox.Show("No Parameter. Exit")
            Exit Sub
        End If
        AddUserName(UserName)
        Me.UserName.Focus()
    End Sub
    Private Sub AddUserName(ByVal MyCB As ComboBox)
        Dim ds As New DataSet
        Dim MyUserName As String = ""
        Dim MySQLStr As String = ""
        Try
            MySQLStr = "Select * FROM WH_LoginSysytem WHERE PROCESS ='WH' or PROCESS ='PL' or PROCESS ='PD' or PROCESS ='IQC' order by UserName"
            ds = MySVRTVNWConnection.ExecuteProcedureSQLTVNWSVR(MySQLStr)
            If ds.Tables.Count <> 0 AndAlso ds.Tables(0).Rows.Count > 0 Then
                For dsindex As Integer = 0 To ds.Tables(0).Rows.Count - 1
                    MyUserName = ds.Tables(0).Rows(dsindex)("UserName")
                    With MyCB
                        .Items.Add(MyUserName)
                    End With
                Next
            End If
        Catch ex As Exception
            ErrRecording("", "AccessControl/AddUserName", ex.Message)
        End Try
    End Sub
    Private Sub ConnectionServerDatabase()
        '  MySVConnection.ExcelConnecting()
        If MySVRTVNWConnection.SVRTVNWConnecting = False Then
            MessageBox.Show("KHONG KET NOI DUOC VOI DATABASE !", "CHU Y!")
            Me.BackColor = Drawing.Color.Yellow
        End If
    End Sub

    Private Sub UserName_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles UserName.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Me.PasswordControl.Focus()
            'Else
            '    Me.UserName.Focus()
        End If
    End Sub

    Private Sub PasswordControl_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles PasswordControl.KeyDown

        If e.KeyCode = 13 Then
            If ScpwFlg = False Then
                AccessSystem()
            ElseIf ScpwFlg = True Then
                Select Case Scpw
                    Case 1
                        OldPW = Me.PasswordControl.Text
                        Scpw = 2
                        Me.lmk.Text = "NHÂP PW MỚI"
                        Me.PasswordControl.Text = ""
                    Case 2
                        NewPW = Me.PasswordControl.Text
                        Scpw = 3
                        Me.lmk.Text = "NHẬP LẠI PW MỚI"
                        Me.PasswordControl.Text = ""
                    Case 3
                        If NewPW = Me.PasswordControl.Text Then
                            If ChangPW() = True Then
                                MessageBox.Show("ĐỔI PASSWORD THÀNH CÔNG")
                            Else
                                MessageBox.Show("ĐỔI PASSWORD KHÔNG THÀNH CÔNG")
                            End If

                        Else
                            MessageBox.Show("2 PASSWORD MỚI KHÔNG TRÙNG NHAU")
                        End If
                        ScpwFlg = False
                        Me.PasswordControl.Text = ""
                        Me.PasswordControl.Focus()
                        Me.lmk.Text = "Mật khẩu"
                End Select

            End If
            'Me.OK.Focus()
        End If
    End Sub


    Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
        AccessSystem()
    End Sub
    Private Sub AccessSystem()
        Dim strUserName As String, strPassWord As String = ""
        Dim MyArrayUserName As New ArrayList
        strUserName = Trim(UserName.Text)
        strPassWord = Trim(PasswordControl.Text)
        CurrentUserName = ""
        CurrentPassword = ""
        If strUserName = "" Then
            'MessageBox.Show("Vui lòng chọn tên người dùng!!!")
            MessageBox.Show("YEU CAU CHON TEN NGUOI DUNG HE THONG")
        ElseIf strPassWord = "" Then
            'MessageBox.Show("Vui lòng nhập  mật khẩu!!!")
            MessageBox.Show("YEU CAU NHAP MAT KHAU DE DANG NHAP HE THONG")
            Me.PasswordControl.Text = ""
            Me.PasswordControl.Focus()
        Else
            Dim ds As New DataSet
            Dim MySQLStr As String = ""
            MySQLStr = "SELECT * FROM WH_LoginSysytem WHERE [UserName] ='" & strUserName & "' and [PassWord] = '" & strPassWord & "' "
            ds = MySVRTVNWConnection.ExecuteProcedureSQLTVNWSVR(MySQLStr)
            If ds.Tables.Count <> 0 AndAlso ds.Tables(0).Rows.Count = 0 Then
                'MessageBox.Show("Sai mật khẩu!!!")
                MessageBox.Show("SAI MẬT KHẨU")
                Me.PasswordControl.Text = ""
                Me.PasswordControl.Focus()
                'ElseIf DecryptPassword(ds.Tables(0).Rows(0)("PassWord")) = strPassWord Then
            ElseIf (ds.Tables(0).Rows(0)("PassWord")) = strPassWord Then
                CurrentUserName = strUserName
                CurrentPassword = strPassWord
                CurrentCode = ds.Tables(0).Rows(0)("Code")
                CurrentProcess = ds.Tables(0).Rows(0)("Process")
                If ds.Tables(0).Rows(0)("Process") = "WH" Then
                    frmMain.Show()
                    Me.Hide()
                    If CurrentCode = "10484" Then
                        Dim MyMessage As String = ("BAN CO MUON DOWN PO TU ACC KO")
                        Dim Result As String = MessageBox.Show(MyMessage, "HI", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)
                        If Result = Windows.Forms.DialogResult.OK Then
                            DownLoadPO()
                        End If
                    End If
                ElseIf ds.Tables(0).Rows(0)("Process") = "PL" AndAlso ds.Tables(0).Rows(0)("Module") = "PO" Then
                    frmPOData.Show()
                    Me.Hide()
                ElseIf ds.Tables(0).Rows(0)("Process") = "IQC" Then
                    frmWIPIQC.Show()
                    Me.Hide()
                ElseIf ds.Tables(0).Rows(0)("Process") = "PL" Or ds.Tables(0).Rows(0)("Process") = "PD" Then
                    frmViewWHData.Show()
                    Me.Hide()
                End If
                Else
                    MessageBox.Show("SAI MAT KHAU")
                    Me.PasswordControl.Text = ""
                    Me.PasswordControl.Focus()
                End If
        End If
        ' FrmPlanning()
    End Sub

    Private Sub PasswordControl_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PasswordControl.TextChanged

    End Sub

    Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Me.lmk.Text = "NHAP PW CU"
        Scpw = 1
        ScpwFlg = True
        Me.UserName.Focus()
    End Sub

    Private Function ChangPW() As Boolean
        Dim MyResult As Boolean = False
        Dim MySQLStr As String = ""
        Dim ds As DataSet
        Dim strUserName As String = ""
        strUserName = Trim(UserName.Text)
        Try
            MySQLStr = "SELECT * FROM WH_LoginSysytem WHERE [UserName] ='" & strUserName & "' and [PassWord] = '" & OldPW & "' "
            ds = MySVRTVNWConnection.ExecuteProcedureSQLTVNWSVR(MySQLStr)
            If ds.Tables.Count <> 0 AndAlso ds.Tables(0).Rows.Count = 1 Then
                MySQLStr = "UPDATE WH_LoginSysytem SET PassWord ='" & NewPW & "' where Code ='" & ds.Tables(0).Rows(0)("Code") & "'"
                If MySVRTVNWConnection.ExecuteSQLTVNWSVR(MySQLStr) = True Then
                    MyResult = True
                End If
            Else
                MyResult = False
            End If
        Catch ex As Exception
            MyResult = False
            ErrRecording("", "AccessControl/ChangPW", ex.Message)
        End Try
        Return MyResult
    End Function

    Private Function GetAddressStr() As Boolean
        Dim MyR As Boolean = False
        Dim MyParameterFile As String = Application.StartupPath & "\Parameter.txt"
        Dim FS As FileStream = Nothing
        Dim FSReader As StreamReader = Nothing
        Try
            If File.Exists(MyParameterFile) Then
                FS = New FileStream(MyParameterFile, FileMode.OpenOrCreate)
                FSReader = New StreamReader(FS)
                FSReader.BaseStream.Seek(0, SeekOrigin.Begin)
                While FSReader.Peek() >= 0
                    Dim MyData As String = FSReader.ReadLine
                    If MyData = "" Then Exit While
                    Dim MySection As String = Mid(MyData, 1, InStr(MyData, "=") - 1)
                    MyR = True
                    Select Case MySection
                        Case "[StockNo]"
                            StockNo = Mid(MyData, InStr(MyData, "=") + 1)
                        Case "[LogfileAdd]"
                            LogfileAdd = Mid(MyData, InStr(MyData, "=") + 1)
                        Case "[IEOAdd]"
                            IEOAdd = Mid(MyData, InStr(MyData, "=") + 1)
                        Case "[PrinterID]"
                            PrinterID = (Mid(MyData, InStr(MyData, "=") + 1))
                        Case "[PrinterA4]"
                            PrinterA4 = (Mid(MyData, InStr(MyData, "=") + 1))
                        Case "[RMP]"
                            RMDP = (Mid(MyData, InStr(MyData, "=") + 1))
                        Case "[EnableStopPLC]"
                        Case Else
                            'MyLocalPicPath = MyPicAddressStr
                    End Select
                End While
            End If
        Catch ex As Exception
            ErrRecording("", "AccessControl/GetAddressStr", ex.Message)
        Finally
            FSReader.Close()
            FSReader.Dispose()
            FS.Close()
            FS.Dispose()
        End Try
        Return MyR
    End Function

    Private Sub UserName_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles UserName.KeyUp
        DPC(UserName, e)
    End Sub

    Private Sub DPC(ByVal CBO As ComboBox, ByVal E As KeyEventArgs)
        Dim R As String = ""
        Dim S As String
        Dim I As Integer
        Dim O As Object
        Dim S2 As String
        Dim S3 As String
        Select Case E.KeyCode
            Case Keys.Back, Keys.Left, Keys.Right, Keys.Up, Keys.Delete, Keys.Down
                Return
        End Select
        S = CBO.Text
        I = CBO.FindString(S)
        If I >= 0 Then
            O = CBO.Items(I)
            S2 = CBO.GetItemText(O)
            S3 = S2.Substring(S.Length)
            CBO.Text = S & S3
            CBO.SelectionStart = S.Length
            CBO.SelectionLength = S3.Length
        End If
    End Sub

    Private Function DownLoadPO() As Boolean
        Dim MyResult As Boolean = False
        Dim MySQLStr As String = ""
        Dim ds As DataSet
        Dim ds1 As DataSet
        Dim dsu As DataSet
        Dim vp As String = ""
        Dim vc As String = ""
        Dim pd As String = ""
        Dim UUU As String = ""
        Try
            If MyDBConnection.DBConnecting = True Then


                MySQLStr = "SELECT * FROM aricst10 "
                ds = MyDBConnection.ExecuteProcedureDBSVR(MySQLStr)
                If ds.Tables.Count <> 0 AndAlso ds.Tables(0).Rows.Count > 0 Then
                    For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                        MySQLStr = "SELECT * from WH_FGCustomer where CDNumber ='" & Trim(ds.Tables(0).Rows(i)("item")) & "'
                        ds1 = MySVRTVNWConnection.ExecuteProcedureSQLTVNWSVR(MySQLStr)
                        If ds1.Tables.Count <> 0 AndAlso ds1.Tables(0).Rows.Count = 0 Then
                            MySQLStr = "INSERT INTO [WH_FGCustomer]([CDNumber],[CustPart],[Cumstomer],[CDUse],[Systemtime])" _
                            & " VALUES ('" & Trim(ds.Tables(0).Rows(i)("item")) & "','" & Trim(ds.Tables(0).Rows(i)("cpartno")) & "','" & Trim(ds.Tables(0).Rows(i)("custno")) & "',1,'" & Now() & "')"
                            If MySVRTVNWConnection.ExecuteSQLTVNWSVR(MySQLStr) = False Then
                                MessageBox.Show("LOI")
                            End If
                        End If
                    Next
                End If

                'MySQLStr = "SELECT potran10.qtyord as Qty, potran10.purno as po, potran10.vendno as vd, potran10.item as p, potran10.vpartno as vp, potran10.descrip as d, pomast10.company as vc FROM pomast10 RIGHT JOIN potran10 ON pomast10.purno = potran10.purno"
                MySQLStr = "SELECT Sum(potran10.qtyord) AS Qty, potran10.purno AS po, potran10.vendno AS vd, potran10.item AS p, potran10.vpartno AS vp, potran10.descrip AS d, pomast10.company AS vc " _
                    & "FROM pomast10 RIGHT JOIN potran10 ON pomast10.purno = potran10.purno " _
                    & " GROUP BY potran10.purno, potran10.vendno, potran10.item, potran10.vpartno, potran10.descrip, pomast10.company"
                ds = MyDBConnection.ExecuteProcedureDBSVR(MySQLStr)
                If ds.Tables.Count <> 0 AndAlso ds.Tables(0).Rows.Count > 0 Then
                    For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                        MySQLStr = "SELECT * from WH_POMaster where PO ='" & Trim(ds.Tables(0).Rows(i)("po")) & "' and  Part ='" & Trim(ds.Tables(0).Rows(i)("p")) & "' "
                        ds1 = MySVRTVNWConnection.ExecuteProcedureSQLTVNWSVR(MySQLStr)
                        If ds1.Tables.Count <> 0 AndAlso ds1.Tables(0).Rows.Count = 0 Then
                            If ds.Tables(0).Rows(i)("vp") Is DBNull.Value = True Then
                                vp = " "
                            Else
                                vp = Replace(Trim(ds.Tables(0).Rows(i)("vp")), "'", "*")
                            End If
                            If ds.Tables(0).Rows(i)("vc") Is DBNull.Value = True Then
                                vc = " "
                            Else
                                vc = Replace(Trim(ds.Tables(0).Rows(i)("vc")), "'", "*")
                            End If
                            If ds.Tables(0).Rows(i)("d") Is DBNull.Value = True Then
                                pd = " "
                            Else
                                pd = Replace(Trim(ds.Tables(0).Rows(i)("d")), "'", "*")
                            End If
                            MySQLStr = "SELECT Item,Unitms FROM arinvt10 where Item = '" & (ds.Tables(0).Rows(i)("p")) & "' "
                            dsu = MyDBConnection.ExecuteProcedureDBSVR(MySQLStr)
                            If dsu.Tables.Count <> 0 AndAlso dsu.Tables(0).Rows.Count = 1 Then
                                UUU = dsu.Tables(0).Rows(0)("Unitms")
                            Else
                                UUU = "NONE"
                                'MessageBox.Show("OO")
                            End If
                            MySQLStr = "INSERT INTO [WH_POMaster]([PO],[Vendno],[Part],[QtyOrd],[PartDes],[UnitPart],[VenderPart],[Company],[SystemTime])" _
                            & " VALUES (" & Trim(ds.Tables(0).Rows(i)("po")) & ",'" & Trim(ds.Tables(0).Rows(i)("vd")) & "','" & Trim(ds.Tables(0).Rows(i)("p")) & "'," & Trim(ds.Tables(0).Rows(i)("Qty")) & ",'" & pd & "','" & UUU & "','" & vp & "','" & vc & "','" & Now() & "')"
                            If MySVRTVNWConnection.ExecuteSQLTVNWSVR(MySQLStr) = False Then
                                MessageBox.Show("LOI")
                            End If

                        End If
                    Next
                End If

                ' MySQLStr = "SELECT poyrcp10.qtyrec as Qty,poyrcp10.purno as po, poyrcp10.vendno as vd, poyrcp10.item as p, poyrcp10.vpartno as vp, poyrcp10.descrip as d, poymst10.company as vc FROM poymst10 RIGHT JOIN poyrcp10 ON poymst10.purno = poyrcp10.purno"

            'MySQLStr = "SELECT poyrcp10.purno as po, poyrcp10.vendno as vd, poyrcp10.item as p, poyrcp10.vpartno as vp, poyrcp10.descrip as d, poymst10.company as vc FROM poyrcp10 INNER JOIN poymst10 ON poyrcp10.purno = poymst10.purno "

            MySQLStr = " SELECT Sum(poyrcp10.qtyrec) AS Qty, poyrcp10.purno AS po, poyrcp10.vendno AS vd, poyrcp10.item AS p, poyrcp10.vpartno AS vp, poyrcp10.descrip AS d, poymst10.company AS vc " _
                                & " FROM poymst10 RIGHT JOIN poyrcp10 ON poymst10.purno = poyrcp10.purno " _
                                & " GROUP BY poyrcp10.purno, poyrcp10.vendno, poyrcp10.item, poyrcp10.vpartno, poyrcp10.descrip, poymst10.company "
                ds = MyDBConnection.ExecuteProcedureDBSVR(MySQLStr)
            If ds.Tables.Count <> 0 AndAlso ds.Tables(0).Rows.Count > 0 Then
                For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                    MySQLStr = "SELECT * from WH_POMaster where PO ='" & Trim(ds.Tables(0).Rows(i)("po")) & "' and  Part ='" & Trim(ds.Tables(0).Rows(i)("p")) & "' "
                    ds1 = MySVRTVNWConnection.ExecuteProcedureSQLTVNWSVR(MySQLStr)
                    If ds1.Tables.Count <> 0 AndAlso ds1.Tables(0).Rows.Count = 0 Then
                        If ds.Tables(0).Rows(i)("vp") Is DBNull.Value = True Then
                            vp = " "
                        Else
                            vp = Replace(Trim(ds.Tables(0).Rows(i)("vp")), "'", "*")
                        End If
                        If ds.Tables(0).Rows(i)("vc") Is DBNull.Value = True Then
                            vc = " "
                        Else
                            vc = Replace(Trim(ds.Tables(0).Rows(i)("vc")), "'", "*")
                        End If
                        If ds.Tables(0).Rows(i)("d") Is DBNull.Value = True Then
                            pd = " "
                        Else
                            pd = Replace(Trim(ds.Tables(0).Rows(i)("d")), "'", "*")
                            End If
                            MySQLStr = "SELECT Item,Unitms FROM arinvt10 where Item = '" & (ds.Tables(0).Rows(i)("p")) & "' "
                            dsu = MyDBConnection.ExecuteProcedureDBSVR(MySQLStr)
                            If dsu.Tables.Count <> 0 AndAlso dsu.Tables(0).Rows.Count = 1 Then
                                UUU = dsu.Tables(0).Rows(0)("Unitms")
                            Else
                                UUU = "NONE"
                                'MessageBox.Show("OO")
                            End If
                            MySQLStr = "INSERT INTO [WH_POMaster]([PO],[Vendno],[Part],[QtyOrd],[PartDes],[UnitPart],[VenderPart],[Company],[SystemTime])" _
                            & " VALUES (" & Trim(ds.Tables(0).Rows(i)("po")) & ",'" & Trim(ds.Tables(0).Rows(i)("vd")) & "','" & Trim(ds.Tables(0).Rows(i)("p")) & "'," & Trim(ds.Tables(0).Rows(i)("Qty")) & ",'" & pd & "','" & UUU & "','" & vp & "','" & vc & "','" & Now() & "')"
                            If MySVRTVNWConnection.ExecuteSQLTVNWSVR(MySQLStr) = False Then
                                MessageBox.Show("LOI")
                            End If
                        End If
                Next

                   
                MessageBox.Show("Download OK")
            End If
            Else
            MyResult = False
            MessageBox.Show("KHÔNG KẾT NỐI SERVER ACCPAC CỤC BỘ.KIEM TRA LAI NHA")
            End If
        Catch ex As Exception
            ErrRecording("", "AccessControl/DownLoadPO", ex.Message)
            MessageBox.Show("LOI. BAO CAP TREN")
        Finally
            If MyDBConnection IsNot Nothing Then
                MyDBConnection.DBClosing()
            End If
        End Try
        Return MyResult
    End Function

    Private Sub UserName_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UserName.SelectedIndexChanged

    End Sub
End Class